var config = require('../../config.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tenantName: "",
    tenantAddress: "",
    tenantLine: "",
    tenantMobile: "",
    webList: [],
    tenantId: null,
    loginUser: null,
    flag: "",
    tab_wd: "map_1_h",
    tab_dt: "",
    mapc: "hide",
    lng: "",
    lat: "",
    name: "",
    addr: "",
    scale: 15,
    showModalStatus: false,
    tabbtn_h: true,
    isLocation : false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // if (app.loginUser == null || app.loginUser.id == null && app.loginUser.mobile == null) {
    //   wx.switchTab({
    //     url: '/pages/login/login'
    //   })
    //   return;
    // }

    var localLongitude = '';
    var localLatitude = '';
    if (app.currentPosition && app.currentPosition.location) {
      localLongitude = app.currentPosition.location.lng;
      localLatitude = app.currentPosition.location.lat;
    }
    this.setData({
      loginUser: app.loginUser,
      tenantId: app.companyInfo.id,
      tenantCode: app.companyInfo.code,
      tenantAddress: app.companyInfo.address,
      tenantLine: app.companyInfo.line,
      tenantName: app.companyInfo.name,
      flag: app.companyInfo.flag,
      localLongitude: localLongitude,
      localLatitude: localLatitude,
      tab_wd: "map_1_h",
      tab_dt: "",
      showView: true,
      mapc: "hide"
    });
  },

  toWebDetail: function(e) {
    let webInfo = e.currentTarget.dataset.type;
    var that = this.data;
    wx.navigateTo({
      url: "webInfo?webInfo=" + JSON.stringify(webInfo)
    })
  },

  /**
   * 拨打电话
   */
  toTelPhone: function(e) {
    var telNo = e.currentTarget.dataset.current;
    wx.makePhoneCall({
      phoneNumber: telNo
    })
  },

  /**
   * 跳转到下单页面
   */
  toAddOrder: function() {
    wx.navigateTo({
      url: '../order/addOrder',
    })
  },
  /**
   * 跳转到取款页面
   */
  toWithdrawal: function() {
    wx.navigateTo({
      url: '../handheldWithdrawals/withdrawalList',
    })
  },
  /**
   * 跳转到货物跟踪页面
   */
  toFreightTrack: function() {
    wx.navigateTo({
      url: '../freightTrack/searchFreightTrack',
    })
  },

  /**
   * 关注物流公司
   */
  followTenant: function() {
    var _this = this;
    var userId = app.loginUser.id;
    if ("" != userId && "" != this.data.tenantId) {
      wx.request({
        url: config.requestUrl + "company/followCompany",
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          "companyId": this.data.tenantId,
          "userId": userId
        },
        success: function(result) {
          app.tip(result.data.msg, 'success');
          _this.setData({
            flag: '1'
          });
        },
        fail: function({
          errMsg
        }) {
          app.tip(errMsg, 'none');
        }
      })
    }
  },
  /**
   * 取消关注物流公司
   */
  cancelFollowTenant: function() {
    var _this = this;
    var userId = app.loginUser.id;
    if ("" != userId && "" != this.data.tenantId) {
      wx.request({
        url: config.requestUrl + "/company/cancelFollowCompany",
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          "companyId": this.data.tenantId,
          "userId": userId
        },
        success: function(result) {
          app.tip(result.data.msg, 'success');
          showView: false;
          _this.setData({
            flag: '0'
          });
        },
        fail: function({
          errMsg
        }) {
          app.tip(errMsg, 'none');

        }
      })
    }
  },
  /**
   * 初始化显示页面数据加载;
   */
  onShow: function () {
    
    var that = this;

    wx.getSetting({
      success: (res) => {
        console.log(res.authSetting['scope.userLocation']);
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] == true) {
          that.setData({
            isLocation : true
          });
        } else {
          that.setData({
            isLocation: false
          });
        }

        if (that.data.tabbtn_h){
          //old:请求后台 getWebList 接口
          //now:寄件网点已经设置到 app.companyInfo.businessSetting 中了，从这里获取即可
          that.setData({
            //获取所有网点
            webList: app.companyInfo.businessSetting.webList,
            showView: true
          });
        }
      }
    });

  },
  /**
   * 点击企业网点
   */
  wangdian: function() {
    this.setData({
      tab_wd: "map_1_h",
      tab_dt: "",
      showView: true,
      mapc: "hide",
      tabbtn_h: true
    });
  },
  /**
   * 点击地图显示
   */
  mapshow: function() {
    // app.companyInfo.longitude = 126.76279;
    // app.companyInfo.latitude = 45.80625;
    showMap(app, this);
  },
  controltap: function(e) {
    var that = this;
    // console.log("scale===" + this.data.scale)
    if (e.controlId === 1) {
      // if (this.data.scale === 13) {
      that.setData({
        scale: --this.data.scale
      })
      // }
    } else {
      //  if (this.data.scale !== 13) {
      that.setData({
        scale: ++this.data.scale
      })
      // }
    }


  },
  /**
   *位置权限
   */
  setLocationSetting: function(e) {
    // console.log(e);
    if (e.detail != undefined && e.detail.authSetting != undefined && e.detail.authSetting["scope.userLocation"] == true) {
      this.data.isLocation = true;
    } else {
      this.data.isLocation = false;
    }
    showMap(app, this);
  },
  /**
   * 导航位置权限
   */
  setLocationSetting_nvato:function(e){
    // console.log(e);
    if (e.detail != undefined && e.detail.authSetting != undefined && e.detail.authSetting["scope.userLocation"] == true) {
      this.data.isLocation = true;
    } else {
      this.data.isLocation = false;
      app.tip("未授权获取位置信息", "none");
    }
    let templng = e.currentTarget.dataset.lng;
    let templat = e.currentTarget.dataset.lat;
    let tempname = e.currentTarget.dataset.name;
    let tempaddr = e.currentTarget.dataset.addr;
    // templng = 126.76279;
    // templat = 45.80625;
    // console.log(templng + "----" + templat);
    if (null == templat || "" == templat || "null" == templat || null == templng || "" == templng || "null" == templng) {
      app.tip("无法获取位置信息！", "none");
      return;
    }

    if (null == tempname || "" == tempname || "null" == tempname) {
      tempname = "";
    }
    if (null == tempaddr || "" == tempaddr || "null" == tempaddr) {
      tempaddr = "";
    }

    this.data.lng = templng;
    this.data.lat = templat;
    this.data.name = tempname;
    this.data.addr = tempaddr;

    wx.openLocation({
      latitude: templat,
      longitude: templng,
      name: tempname,
      address: tempaddr,
      scale: 15
    })
  },
  /**
   * 点击导航
   */
  navTo: function(e) {
    // console.log(e.currentTarget.dataset.lat + "----" + e.currentTarget.dataset.lng);
    // console.log(e.currentTarget.dataset.name + "----" + e.currentTarget.dataset.addr);
    if (this.data.isLocation == false){
      app.tip("未授权获取位置信息", "none");
    }
    let templng = e.currentTarget.dataset.lng;
    let templat = e.currentTarget.dataset.lat;
    let tempname = e.currentTarget.dataset.name;
    let tempaddr = e.currentTarget.dataset.addr;
    // templng = 126.76279;
    // templat = 45.80625;
    // console.log(templng + "----" + templat);
    if (null == templat || "" == templat || "null" == templat || null == templng || "" == templng || "null" == templng) {
      app.tip("无法获取位置信息！", "none");
      return;
    }

    if (null == tempname || "" == tempname || "null" == tempname) {
      tempname = "";
    }
    if (null == tempaddr || "" == tempaddr || "null" == tempaddr) {
      tempaddr = "";
    }

    this.data.lng = templng;
    this.data.lat = templat;
    this.data.name = tempname;
    this.data.addr = tempaddr;

    wx.openLocation({
	    latitude: templat,
	    longitude: templng,
	    name: tempname,
	    address: tempaddr,
	    scale: 15
	  })

    // 126.76279----45.80625
    // 126.56279-- - 45.80825
  }
});

function showMap(app, _this) {
  // app.companyInfo.longitude = 126.76279;
  // app.companyInfo.latitude = 45.80625;
  if (app.companyInfo.longitude == null || "" == app.companyInfo.longitude || "null" == app.companyInfo.longitude && null == app.companyInfo.latitude || "" == app.companyInfo.latitude || "null" == app.companyInfo.latitude) {
    app.tip("无法获取位置信息！", "none");
    return;
  }
  if (_this.data.isLocation == false) {
    app.tip('未授权获取位置信息', 'none');
  }
  // let _this = this;
  // console.log(app.companyInfo.longitude + "---" + app.companyInfo.latitude);
  _this.setData({
    tab_wd: "",
    tab_dt: "map_2_h",
    showView: false,
    mapc: "show",
    tabbtn_h: false,
    isLocation: _this.data.isLocation,
    lng: app.companyInfo.longitude,
    lat: app.companyInfo.latitude,
    controls: [{
        id: 1,
        iconPath: '../images/jian.png',
        position: {
          left: 260,
          top: 20,
          width: 30,
          height: 30
        },
        clickable: true
      },
      {
        id: 2,
        iconPath: '../images/jia.png',
        position: {
          left: 310,
          top: 20,
          width: 30,
          height: 30
        },
        clickable: true
      }
    ],
    markers: [{
      id: "1",
      label: {
        content: app.appName,
        textAlign: "center",
        color: "#9932CC"
      },
      latitude: app.companyInfo.latitude,
      longitude: app.companyInfo.longitude,
      width: 50,
      height: 50,
      iconPath: "",
      title: app.appName
    }]
  });
}